<?php

namespace App\Http\Controllers\Publishing;

use App\Contracts\Services\Storage\StorageService;
use App\Entities\Activity;
use App\Entities\ActivityPublishing;
use App\Entities\PublishingAccount;
use App\Morefun\Publishing\Publisher;
use Illuminate\Container\Container;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Ramsey\Uuid\Uuid;

class WebApiController
{
    public function publish(Request $request, Publisher $publisher, $activityId)
    {
        if (!Uuid::isValid($activityId)) {
            return response()->failed('您所发布的活动不合法');
        }

        if (!Activity::query()->where('id', $activityId)->exists()) {
            return response()->failed('您所发布的活动不存在');
        }
        $inputs = $request->json()->all();
        if ($success = $publisher->publish($activityId, $inputs)) {
            return response()->success($success);
        }

        return response()->failed();
    }

    public function getPublished($activityId)
    {
        $storage = Container::getInstance()->make(StorageService::class);
        $publishingWays = Activity::query()->where('id', $activityId)->value('publishing_ways');
        if (!$publishingWays) {
            $default = ['app' => ['is_open' => 'off'], 'wechat' => ['is_open' => 'off']];
            return response()->success($default);
        }

        $ways = json_decode($publishingWays, true);
        $qrCodes = Arr::get($ways, 'wechat.qr_code', []);
        $codes = [];

        foreach ($qrCodes as $code) {
            $codes[] = $storage->toHttpUrl($code);
        }

        Arr::set($ways, 'wechat.qr_code', $codes);

        return response()->success($ways);
    }
}
